<template>
	<view class="main">
		<u-cell-group>
			<view style="background: white">
				<u--text type="info" text="消息通知设置"></u--text>
			</view>
			<u-cell :border="false" size="large" :value="officialRemarkName" isLink @click="toPageMessagePush()">
				<text slot="title" class="u-cell-text">接收公众号消息</text>
			</u-cell>
			<view v-for="(item,index) in pushConfigList" :key="index" style="background: white">
				<u--text type="info" :text="item.name"></u--text>
				<view v-for="(data,indexChild) in item.childList" :key="indexChild">
					<u-cell :border="false" size="large" :label="data.labelDesc">
						<view slot="title" class="u-flex-center">
							<text class="u-cell-text">{{data.name}}</text>
							<view class="u-m-l-20" v-if="data.type == 16"><u-button @click="nav()" type="primary"
									size="mini" text="设置"></u-button></view>
						</view>
						<u-switch v-model="data.isOpen" @change="isOpenChange(data,TYPE.OFFICIAL)" :activeColor="aColor"
							slot="value"></u-switch>
					</u-cell>
				</view>
			</view>
		</u-cell-group>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pushConfigList: [],
				appletPushConfigList: [],
				aColor: '#6072FF',
				storageKeyEnum: this.$storageKeyEnum,
				officialRemarkName: '',
				appletRemarkName: '',
				TYPE: {
					OFFICIAL: 1,
					APPLET: 2,
				}
			}
		},
		onShareTimeline(res) {},
		onLoad(options) {
			this.findPushConfigList();
			this.findAppletPushConfigList();
			this.findAppletOrOfficialAccountRemarkName(true);
		},
		onShow() {
			if (uni.getStorageSync(this.storageKeyEnum.binding_successful)) {
				this.findWhetherToSetWechatNotification();
			}
		},
		methods: {
			nav() {
				uni.navigateTo({
					url: '/pages-other/stock-notice/stock-notice',
				});
			},
			findAppletOrOfficialAccountRemarkName(flog) {
				this.$api('appletOrOfficialAccount.findAppletOrOfficialAccountRemarkName').then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						console.log("res.data", res.data)
						this.officialRemarkName = res.data.officialRemarkName
						this.appletRemarkName = res.data.appletRemarkName
						if (!flog) {
							this.$helpers.toast('绑定成功')
						}
					}
				})
			},
			openPopup(data, appletOrOfficialType, index) {
				console.log(data)
				this.findOneByWeChatAppId(data, appletOrOfficialType, index);
			},
			//校验是否可以开启推送消息
			findOneByWeChatAppId(data, appletOrOfficialType, index) {
				// console.log('appId:', uni.getAccountInfoSync().miniProgram.appId)
				// console.log('type:', data.type)
				this.$api('appletOrOfficialAccount.subscribeAuthorizeByAppId', {
					appId: uni.getAccountInfoSync().miniProgram.appId,
					type: data.type
				}).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						if (res.data) {
							let templateIdOneArray = new Array;
							templateIdOneArray.push(res.data.templateId)
							if (!data.isOpen) {
								this.isOpenChange(data, appletOrOfficialType);
								return
							}
							this.subscribeToOrderUpdates(templateIdOneArray, data, appletOrOfficialType);
						} else {
							this.$helpers.toast('当前小程序暂未配置通知功能', 'none', 3000, true, () => {
								this.findAppletPushConfigList();
							});
						}
					}
				})
			},
			// 点击订阅按钮的事件处理函数
			subscribeToOrderUpdates(templateIdOneArray, data, appletOrOfficialType) {
				let _this = this;
				console.log("templateIdArray", templateIdOneArray)
				wx.requestSubscribeMessage({
					tmplIds: templateIdOneArray,
					success(res) {
						console.log("res", res)
						if (res[templateIdOneArray] === 'accept') {
							console.log(`用户认可的 ${templateIdOneArray}`);
							//开启了订阅就去获取用户的openId,修改用户信息
							//_this.getOpenIdUpdateUser()
							wx.getSetting({
								withSubscriptions: true,
								success(res) {
									console.log('用户', res)
									console.log('用户', res.subscriptionsSetting)
									console.log("用户订阅的模板", res.subscriptionsSetting.itemSettings)
								}
							})
							_this.isOpenChange(data, appletOrOfficialType);
						} else {
							console.log(`用户被拒绝 ${templateIdOneArray}`);
							_this.findAppletPushConfigList();
						}

					},
					fail(err) {
						console.error(err);
					}
				});
			},
			getOpenIdUpdateUser() {
				let _this = this;
				// 用户同意订阅
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let params = {
							code: loginRes.code,
							appId: uni.getAccountInfoSync().miniProgram.appId
						}
						_this.$api('user.sendSubscribe', params).then(res => {
							if (res.status == 0) {
								//获取接收接受消息的平台名称
								_this.findAppletOrOfficialAccountRemarkName();
							}
						})
					}
				})
			},

			isOpenChange(data, type) {
				let params = {
					pushConfigId: data.id,
					isOpen: data.isOpen,
					type: type,
				}
				console.log("data", data)
				console.log("params", params)
				// return
				this.$api('pushConfigItem.editOnePushConfigItem', params).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						this.$helpers.toast(data.isOpen ? '开启成功' : '关闭成功');
					} else {
						this.$helpers.toast('关闭失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			findPushConfigList() {
				uni.showLoading({
					title: '加载中...'
				})
				let param = {
					appletOrOfficialType: this.TYPE.OFFICIAL
				}
				this.$api('pushConfig.findPushConfigList', param).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						//公众号
						this.pushConfigList = res.data;
					} else {
						this.$helpers.toast('查询推送消息失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			findAppletPushConfigList() {
				uni.showLoading({
					title: '加载中...'
				})
				let param = {
					appletOrOfficialType: this.TYPE.APPLET
				}
				this.$api('pushConfig.findPushConfigList', param).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						//小程序
						this.appletPushConfigList = res.data;
					} else {
						this.$helpers.toast('查询推送消息失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			// 判断微信通知是否已设置
			findWhetherToSetWechatNotification() {
				this.$api('user.findWhetherToSetWechatNotification').then(res => {
					if (res.status == 0) {
						this.$helpers.toast("绑定成功")
						uni.removeStorageSync(this.storageKeyEnum.binding_successful);
					} else {
						getApp().err(res.msg);
					}
				}).catch(err => {
					console.error(err.toString())
				})
			},
			toPageMessagePush(url) {
				this.$api('device.getDeviceByManufacturers', null).then(res => {
					if (res.status == 0) {
						uni.setStorageSync(this.storageKeyEnum.binding_successful, true);
						let u = '/pages-other/message/message-notification-check?appletOrOfficialAccountId=';
						if (res.data) {
							u = u + res.data;
						}
						uni.navigateTo({
							url: u,
						});
					} else {
						getApp().err(res.msg);
					}
				}).catch(err => {
					console.error(err.toString())
				})

			},
			toPage(url) {
				uni.navigateTo({
					url: url,
				});
			}
		}
	}
</script>

<style lang="scss">
	/deep/.u-cell {
		background-color: white;
	}

	/deep/.u-cell__title-text--large {
		font-size: 30rpx !important;
	}

	/deep/.u-text {
		font-size: 26rpx;
		padding: 20rpx 25rpx 10rpx 25rpx;
	}

	.main {
		table-layout: fixed;  
		word-break: break-all;  
		overflow: hidden;
		padding-bottom: 60rpx;

		.u-cell-text {
			padding: 20rpx 0;
		}
	}
</style>
